package com.taotao.designpattern.state.multi;

import com.google.common.collect.HashBasedTable;
import com.taotao.designpattern.state.Event;
import com.taotao.designpattern.state.State;

import java.util.List;

abstract class AbstructStateMachine {

    /**
     * 处理器
     */
    static class SopExec {
        private State nextState;
        private IStateHandle stateHandle;

        public State getNextState() {
            return nextState;
        }

        public void setNextState(State nextState) {
            this.nextState = nextState;
        }

        public IStateHandle getStateHandle() {
            return stateHandle;
        }

        public void setStateHandle(IStateHandle stateHandle) {
            this.stateHandle = stateHandle;
        }
    }

    private static HashBasedTable<State, Event, SopExec> hashBasedTable = HashBasedTable.create();

    {
        List<SopProcess> sopProcesses = init();
        sopProcesses.forEach(item -> {
            SopExec sopExec = new SopExec();
            sopExec.setNextState(item.getTo());
            sopExec.setStateHandle(item.getStateHandle());
            hashBasedTable.put(item.getFrom(), item.getEvent(), sopExec);
        });
    }

    abstract List<SopProcess> init();

    public State getNext(State state, Event event) {
        SopExec result = hashBasedTable.get(state, event);
        if (result == null) {
            throw new IllegalArgumentException("未找到状态");
        }
        return result.getNextState();

    }

    public IStateHandle getHandle(State state, Event event) {
        SopExec result = hashBasedTable.get(state, event);
        if (result == null) {
            throw new IllegalArgumentException("未找到状态");
        }
        return result.getStateHandle();
    }

}
